<template>
	<div class="SingleChoice-components">
		<div v-if="data.questionAnswerContent && explain">
			<p class="ques-title">{{ data.questionAnswerContent.question }}</p>
			<van-radio-group v-model="answer">
				<van-radio
					disabled
					:class="[data.questionAnswerContent.score ? 'right-one' : 'error-one']"
					:name="index"
					v-for="(item, index) in data.questionAnswerContent.choiceAndAnswerList"
					:key="index"
					>{{ item.choice }}</van-radio
				>
			</van-radio-group>
			<p
				class="ques-title"
				style="font-weight: bold"
				v-show="!data.questionAnswerContent.score"
			>
				正确答案：
				<span style="color: #56baca">
					{{ data.questionAnswerContent.answer | numFilter }}
				</span>
			</p>
		</div>
		<div v-if="data.content && !explain">
			<p class="ques-title">{{ data.content.question }}</p>

			<van-radio-group v-model="answer">
				<van-radio
					:name="index"
					v-for="(item, index) in data.content.choiceAndAnswerList"
					:key="index"
					>{{ item.choice }}</van-radio
				>
			</van-radio-group>
			<slot></slot>
		</div>
	</div>
</template>
<script>
export default {
	name: "SingleChoice",
	props: {
		data: {
			type: Object,
			default: {},
		},
		explain: {
			type: Boolean,
			default: false,
		},
	},
	data() {
		return {
			answer: "",
		};
	},
	watch: {
		data: {
			handler(newV, oldV) {
				this.initState();
			},
			deep: true,
		},
	},
	mounted() {
		this.initState();
	},
	methods: {
		initState() {
			if (this.explain) {
				if (this.data.questionAnswerContent) {
					this.answer = this.data.questionAnswerContent.studentAnswer;
				} else {
					this.filterRight();
				}
			} else {
				this.answer = this.data.answer;
			}
		},
		filterRight() {
			this.data.questionAnswerContent = JSON.parse(JSON.stringify(this.data.questionContent));
			this.data.questionContent.choiceAndAnswerList.forEach((element, index) => {
				if (element.answer) {
					this.data.questionAnswerContent.answer = index;
				}
			});
		},
		computeScore() {
			var score = 0;
			var content = JSON.parse(JSON.stringify(this.data.content));
			content.choiceAndAnswerList.forEach((element, index) => {
				if (element.answer) {
					content.answer = index;
				}
				if (this.answer === index) {
					score = element.answer ? this.data.totalScore : 0;

					element.answer = true;
				} else {
					element.answer = null;
				}
			});
			content.score = score;

			content.finish = this.$isFull(this.answer);
			content.studentAnswer = this.answer;
			return { content, score };
		},
		changeValue(key) {
			var { content, score } = this.computeScore();
			this.$emit("changeValue", this.answer, content, score);
		},
	},
};
</script>

<style lang="scss">
.SingleChoice-components {
}
</style>
